<template>
  <page-wrap back title="附件简历" hide-tab stayStill :hideSafeArea="true">
    <view class="resume">
      <view class="topBox">
        <text class="text_title"> {{ textTitle }}</text>
        <view class="fillBox"></view>
        <span class="diagnosisRecord" @click="clickRecordList">评定记录</span>
      </view>

      <template v-if="isUploaded">
        <view class="cellContainer">
          <u-cell-group class="cell_group">
            <view
              v-for="item in resumeList"
              :key="item.id"
              :class="{ 'resume-list-item': true }"
              @click="handleResumeClick(item)"
            >
              <u-cell-item
                :title="item.attName"
                value="上传成功"
                :arrow="false"
                :title-style="fileTitleStyle"
                :value-style="statusTextStyle"
                title-width="380"
              >
                <!-- <u-icon slot="icon" size="100" name="icon-select"></u-icon> -->
                <text
                  slot="icon"
                  class="icon icon-select"
                  :class="{ selected: selectedResume.id == item.id }"
                ></text>
              </u-cell-item>
            </view>
          </u-cell-group>
        </view>
        <view class="tipsContainer">
          <text class="text_tip">
            注：为保证顾问的服务效率，目前仅支持doc、docx、pdf格式文件，请您上传的文件尽可能小于10M</text
          >
        </view>
        <text class="btn_protocol_text,u-text-center" @tap="textClickProtocol">
          活动详情查看《简历诊断服务协议》</text
        >
        <!-- <view  class="btn_protocol_text,u-text-center">
                <u-link  href="http://www.baidu.com" color="gray">活动详情查看《简历诊断服务协议》</u-link>
              </view> -->
        <u-button
          type="error"
          plain="true"
          hover-class="none"
          class="btn_upload_orther"
          @click="btnClickUpload"
          >选择其它简历文件</u-button
        >
      </template>
      <template v-else>
        <view class="noResumeTips">
          <span
            >注：推荐您点击“生成附件简历”按钮，完善在线简历后生成一份自己的附件简历，使用这份简历进行简历诊断服务</span
          >
          <view class="toGenerateResume" @click="toGenerateResume"
            >生成附件简历</view
          >
        </view>
        <view class="img-wrap">
          <image :src="exampleImg"></image>
        </view>
      </template>
      <u-button type="error" class="btn_upload" @click="btnClickAssessment">{{
        redBtnTitle
      }}</u-button>
    </view>
  </page-wrap>
</template>

<script>
import {
  uploadResumeFuJianToDiagnose,
  getResumeFuJianOnDiagnose,
  deleteResumeFuJian,
  uploadAction,
  uploadBaseUrl,
  getResumeFuJianDiagnoseStatus,
  addPersonAddAttachment
} from '@/api/index';
import ShareMixin from '@/mixins/share';
export default {
  mixins: [ShareMixin],
  data() {
    return {
      selectedResume: {},
      isUploaded: false,
      img1: this.$imgBaseSelf + 'career/diagnosis/1.png',
      exampleImg: this.$imgBaseSelf + 'resume/example.png?v=1',
      appendixImg: this.$imgBaseSelf + 'resume/appendix.svg',
      personId: uni.getStorageSync('person-id').slice(2) || undefined,

      // personId:'24192616',

      redBtnTitle: '选择文件',
      textTitle: '检测到您还为未上传附件简历：',
      fileTitle: '文件名1',
      fileTitleStyle: {
        color: '#333333',
        fontSize: '36rpx',
        wordBreak: 'break-all'
      },
      statusTextStyle: {
        color: '#84B63C',
        fontSize: '24rpx'
      },
      resumeList: [
        // {
        //   diagnoseRecordId: 1,
        //   resumeName: "附件简历",
        //   resumeSimpleName: "附件简历", // 过长就省略号
        //   resume: "https://xxx",
        // },
      ],
      linkUrl:
        'https://img3.job1001.com/ypMp/elan/files/resume_diagnosis_service_agreement.pdf',
      fromWhere: 'discovery'
    };
  },
  onLoad(options) {
    this.fromWhere = options.fromWhere || 'discovery'; // 如果没有传，默认是从“发现”进来，要付费
  },
  created() {
    this.getPersonFuJianList();
  },
  methods: {
    toGenerateResume() {
      uni.navigateTo({
        url: '/pagesSub/newResume/index'
      });
    },
    handleResumeClick(item) {
      this.selectedResume = item;
    },
    //查看简历评定的历史报告
    clickRecordList() {
      uni.navigateTo({ url: '/pagesSub/resume/diagnosisHistory/index' });
    },

    textClickProtocol() {
      // let url = `/pagesSub/public/web/index?title=简历诊断服务协议&link=${encodeURIComponent(this.linkUrl)}`;
      // uni.navigateTo({ url });

      uni.navigateTo({
        url: '/pagesSub/career/activity/resumeDiagnosisService'
      });
    },
    // 上传附件
    btnClickUpload() {
      if (this.resumeList.length > 2) {
        this.$u.toast('最多上传3个简历！');
        return;
      }
      this.handleUpload();
    },
    // 订阅审核通知
    subscribeMessage() {
      if (!this.selectedResume.id) {
        this.$u.toast('请选择简历！');
        return;
      }
      uni.requestSubscribeMessage({
        tmplIds: ['aRgtnpYL5P6fXRO53Zw5nU7TRm0Q--p1iq8BtQhU1xs'],
        complete: (res) => {
          console.log(res);
          this.startToDiagnose();
        }
      });
    },
    // 开始评审
    btnClickAssessment() {
      if (this.isUploaded == true) {
        this.subscribeMessage();
      } else {
        this.btnClickUpload();
      }
    },

    // 获取简历列表数据
    getPersonFuJianList() {
      let param = {
        personId: this.personId,
        companyId: this.personId,
        attStatus: 1
      };
      let that = this;
      getResumeFuJianOnDiagnose(param).then((res) => {
        if (res.code === 200) {
          let array = res.data;
          console.log('res.data', res.data);

          if (Array.isArray(res.data)) {
            if (!res.data.length) return;
            that.resumeList = res.data;
            that.redBtnTitle = '开始评定';
            that.textTitle = '即将对以下附件简历进行评定：';
            that.isUploaded = true;
            // this.handleResumeClick(res.data[0]);
            return;
          }
          if (res.data.resume) {
            console.log('有值');
            let name = res.data.resumeName;
            if (name.length > 10) {
              res.data.resumeSimpleName = name.slice(0, 10) + '...';
            } else {
              res.data.resumeSimpleName = name;
            }
            // that.resumeList = res.data;
            // that.redBtnTitle = "开始评定";
            // that.textTitle = "即将对以下附件简历进行评定：";
            // that.isUploaded = true;
          }
        }
      });
    },

    // 选择本地文件
    handleUpload() {
      // #ifdef H5
      var uploadApi = uni.chooseFile;
      // #endif
      // #ifdef MP-WEIXIN
      var uploadApi = wx.chooseMessageFile;
      // #endif
      const TYPE = ['.doc', '.docx', '.png', '.jpg', '.jepg', '.png', '.pdf'];
      let that = this;
      uploadApi({
        count: 1, //默认100
        extension: TYPE,
        success: (res) => {
          let tempFilePaths = res.tempFiles;
          let fileExt = '.' + tempFilePaths[0].name.replace(/.+\./, '');
          if (TYPE.indexOf(fileExt) < 0) {
            return uni.showToast({
              icon: 'none',
              title: '文件类型错误'
            });
          }
          if (tempFilePaths[0].size / (1024 * 1024) > 10) {
            return uni.showToast({
              icon: 'none',
              title: '文件大小不能超过10M'
            });
          }
          uni.showLoading({
            title: '正在上传'
          });
          uni.uploadFile({
            url: uploadAction,
            filePath: tempFilePaths[0].path,
            name: 'file',
            success: (uploadRes) => {
              console.log(
                '🚀 ~ file: AttachmentUpload.vue:169 ~ handleUpload ~ uploadRes:',
                uploadRes
              );
              uni.showToast({
                icon: 'none',
                title: '上传成功'
              });

              let name = tempFilePaths[0].name;
              if (name.length > 10) {
                name = name.slice(0, 10) + '...';
              }
              let info = {
                resume: uploadBaseUrl + uploadRes.data,
                resumeName: tempFilePaths[0].name,
                resumeSimpleName: name
              };
              console.log(
                '🚀 ~ file: AttachmentUpload.vue:177 ~ handleUpload ~ info:',
                info
              );

              console.log('有文件了');
              //还要发送给后端保存...
              that.saveResume(info);
              // that.resumeList.push([info]);
              that.redBtnTitle = '开始评定';
              that.textTitle = '即将对以下附件简历进行评定：';
              that.isUploaded = true;
            }
          });
        }
      });
    },
    saveResume(info) {
      const params = {
        personId: this.personId,
        attName: info.resumeName,
        attUrl: info.resume
      };
      addPersonAddAttachment(params).then((res) => {
        if (res.code == 200) {
          this.getPersonFuJianList();
        }
      });
    },
    // 开始评定
    startToDiagnose() {
      const id = uni.getStorageSync('openid');
      let info = this.resumeList[0];
      let param = {
        personId: this.personId,
        resumeName: this.selectedResume.attName,
        openId: id
      };
      if (this.selectedResume.uploadType == 2) {
        param.resumeType = 1;
        param.resumeUrl = this.selectedResume.attUrl;
      } else {
        param.resumeType = 2;
        param.relId = this.selectedResume.id;
      }
      if (this.fromWhere == 'discovery') {
        param.diagnoseSource = 0;
      } else if (this.fromWhere == 'careerPath') {
        param.diagnoseSource = 1;
      } else {
        // 这个是为了扩展以后的不同来源而做的
        param.diagnoseSource = 0;
      }
      // console.log(param);
      uploadResumeFuJianToDiagnose(param).then((fujianRes) => {
        uni.hideLoading();
        if (fujianRes.code === 200) {
          uni.redirectTo({
            url: `/pagesSub/newResume/resumeAssessment/index?target=AIResumeDiagnoseNew`
          });
        } else {
          this.$u.toast('请求失败，请稍候再试(202)');
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.resume {
  position: relative;

  .topBox {
    // top: 60rpx;
    padding-top: 60rpx;
    padding-left: 40rpx;
    padding-right: 40rpx;
    display: flex;
    flex-direction: row;
    // align-items: left;
    .fillBox {
      flex: 1;
      height: 1px;
    }
    .diagnosisRecord {
      color: red;
    }
  }

  .text_title {
    // position: absolute;
    //left: 40rpx;
    //top: 60rpx;
  }
  .cellContainer {
    padding: 40rpx 40rpx;
    .cell_group {
      top: 130rpx;
      .resume-list-item {
        box-sizing: border-box;
        .icon {
          margin-right: 20rpx;
          &-select {
            width: 28rpx;
            height: 28rpx;
            background-image: url($img-base + 'rights/select.png');
            background-size: 100% 100%;
            &.selected {
              background-image: url($img-base + 'rights/selected.png');
            }
          }
        }
      }
      .selecetedResume {
        border: 1px solid blue;
      }
    }
  }
  .tipsContainer {
    display: flex;
    padding: 0rpx 40rpx;
    .text_tip {
      word-break: break-all;
      flex: 1 1 auto;
      // left: 40rpx;
      // top: 300rpx;
      color: gray;
    }
  }

  .btn_protocol_text {
    font-size: 24rpx;
    width: 100%;
    justify-content: center;
    position: fixed;
    bottom: 260rpx;
    color: gray;
  }
  .btn_upload {
    left: 40rpx;
    right: 40rpx;
    position: fixed;
    bottom: 60rpx;
  }

  .btn_upload_orther {
    left: 40rpx;
    right: 40rpx;
    position: fixed;
    bottom: 160rpx;
  }
  .noResumeTips {
    display: flex;
    margin-top: 40rpx;
    padding: 0 40rpx;
    & > span {
      max-width: 65%;
    }
    & > view {
      margin-left: 40rpx;
      width: 260rpx;
      min-width: 260rpx;
      height: 80rpx;
      padding: 20rpx 20rpx;
      text-align: center;
      background-color: red;
      color: white;
      border-radius: 22rpx;
    }
  }
  .img-wrap {
    flex-grow: 1;
    display: flex;
    justify-content: center;
    top: 12rpx;
    position: inherit;
    image {
      width: 694rpx;
      height: 1043rpx;
    }
  }
}
</style>
